package com.xhlj.security.captcha;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.xhlj.utils.Result;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CaptchaLoginAuthenticationFilter extends OncePerRequestFilter {
    /*感觉filter白写了,
     * 这样Controller手动的话根本不用filter
     * 不是的我们这个filter其实还是有用的,只不过和Controller那边重复了,报了一个Servlet的错误,这用的话可以使用还是Controller
     * 这个Filter我没有指定路径,其实所用的请求,都会走一遍这个,你只要参数你带上那个就行
     * 可以再doFilterInterval中去过滤路径
     * */
    /*容易出现循环依赖,所以filter才不建议给ioc管理*/
    AuthenticationManager authenticationManager;

    public CaptchaLoginAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        /*请求体只能读取一次,filter在Controller之前执行,你这边读取以后Controller那边就不好说了*/

        String phone = request.getParameter("username");
        String captcha = request.getParameter("captcha");
        if (!StringUtils.isEmpty(phone) && !StringUtils.isEmpty(captcha)) {
            List<GrantedAuthority> authorities = new ArrayList<>();
            CaptchaLoginAuthenticationToken captchaLoginAuthenticationToken = new CaptchaLoginAuthenticationToken(phone, captcha, authorities);
            Authentication authentication = authenticationManager.authenticate(captchaLoginAuthenticationToken);

            Map principal = (Map) authentication.getPrincipal();
            String username = (String) principal.get("phone");
            Map res = new HashMap();
            res.put("username", username);
            response.setContentType("application/json;charset=UTF-8");
//          getWriter只能调用一次的,这样子应该能用,只是
            response.getWriter().print(JSON.toJSONString(Result.ok(res)));
            return;
        }
        filterChain.doFilter(request, response);
    }
}
